package StackAndQueue;

import java.util.*;

public class p347前K个高频元素 {
    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            // {元素，出现次数}
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, map.getOrDefault(num, 0) + 1);
            }
            // 从大到小排列
            PriorityQueue<int[]> pq = new PriorityQueue<>((p1, p2) -> p2[1] - p1[1]);
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                pq.add(new int[]{entry.getKey(), entry.getValue()});
            }
            int[] ans = new int[k];
            for (int i = 0; i < k; i++) {
                ans[i] = pq.poll()[0];
            }
            return ans;
        }
    }
}
